const { Caregiver, User, Order } = require('../models');
const { AppError } = require('../middleware/errorHandler');
const logger = require('../utils/logger');
const { validationResult } = require('express-validator');
const { Op } = require('sequelize');
const catchAsync = require('../utils/catchAsync'); // 添加 catchAsync 导入
const multer = require('multer');
const sharp = require('sharp');
const path = require('path');
const fs = require('fs').promises;

// 配置 multer 用于文件上传
const multerStorage = multer.memoryStorage();

const multerFilter = (req, file, cb) => {
  if (file.mimetype.startsWith('image')) {
    cb(null, true);
  } else {
    cb(new AppError('请上传图片文件', 400), false);
  }
};

const upload = multer({
  storage: multerStorage,
  fileFilter: multerFilter,
  limits: {
    fileSize: 5 * 1024 * 1024 // 5MB
  }
});

// 上传证书照片
exports.uploadCertificates = upload.array('certificates', 5);

// 处理证书照片
exports.processCertificates = async (req, res, next) => {
  try {
    if (!req.files || req.files.length === 0) return next();

    req.body.certificatePhotos = [];

    await Promise.all(
      req.files.map(async (file, i) => {
        const filename = `caregiver-${req.user.id}-cert-${i + 1}-${Date.now()}.jpeg`;
        const filepath = path.join('public', 'img', 'certificates', filename);

        // 确保目录存在
        await fs.mkdir(path.dirname(filepath), { recursive: true });

        await sharp(file.buffer)
          .resize(800, 600)
          .toFormat('jpeg')
          .jpeg({ quality: 90 })
          .toFile(filepath);

        req.body.certificatePhotos.push(filename);
      })
    );

    next();
  } catch (error) {
    logger.error('处理证书照片错误:', error);
    return next(new AppError('处理证书照片失败', 500));
  }
};

// 获取当前护理员信息
exports.getMyProfile = async (req, res, next) => {
  try {
    const caregiver = await Caregiver.findOne({
      where: { userId: req.user.id },
      include: [{
        model: User,
        as: 'user',
        attributes: ['id', 'firstName', 'lastName', 'email', 'phone', 'avatar']
      }]
    });

    if (!caregiver) {
      return next(new AppError('护理员信息不存在', 404));
    }

    res.status(200).json({
      status: 'success',
      data: {
        caregiver
      }
    });
  } catch (error) {
    logger.error('获取护理员信息错误:', error);
    return next(new AppError('获取护理员信息失败', 500));
  }
};

// 创建护理员档案
exports.createProfile = async (req, res, next) => {
  try {
    // 检查验证错误
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return next(new AppError('输入数据验证失败', 400));
    }

    // 检查用户是否已经有护理员档案
    const existingCaregiver = await Caregiver.findOne({ where: { userId: req.user.id } });
    if (existingCaregiver) {
      return next(new AppError('您已经创建了护理员档案', 400));
    }

    // 创建护理员档案
    const caregiverData = {
      userId: req.user.id,
      ...req.body
    };

    // 如果有上传的证书照片
    if (req.body.certificatePhotos) {
      caregiverData.certificates = caregiverData.certificates || [];
      req.body.certificatePhotos.forEach((photo, index) => {
        if (caregiverData.certificates[index]) {
          caregiverData.certificates[index].photo = photo;
        }
      });
    }

    const caregiver = await Caregiver.create(caregiverData);
    
    await caregiver.reload({
      include: [{
        model: User,
        as: 'user',
        attributes: ['id', 'firstName', 'lastName', 'email', 'phone', 'avatar']
      }]
    });

    // 更新用户角色
    await User.update(
      { role: 'caregiver' },
      { where: { id: req.user.id } }
    );

    logger.info(`创建护理员档案: ${req.user.email}`);

    res.status(201).json({
      status: 'success',
      message: '护理员档案创建成功',
      data: {
        caregiver
      }
    });
  } catch (error) {
    logger.error('创建护理员档案错误:', error);
    return next(new AppError('创建护理员档案失败', 500));
  }
};

// 更新护理员档案
exports.updateProfile = async (req, res, next) => {
  try {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return next(new AppError('输入数据验证失败', 400));
    }

    const caregiver = await Caregiver.findOne({ where: { userId: req.user.id } });
    if (!caregiver) {
      return next(new AppError('护理员档案不存在', 404));
    }

    const allowedFields = [
      'experience', 'skills', 'certificates', 'serviceArea', 'availability',
      'pricing', 'insurance', 'emergencyContact', 'preferences'
    ];
    
    const updateData = {};
    allowedFields.forEach(field => {
      if (req.body[field] !== undefined) {
        updateData[field] = req.body[field];
      }
    });

    if (req.body.certificatePhotos) {
      updateData.certificates = updateData.certificates || caregiver.certificates;
      req.body.certificatePhotos.forEach((photo, index) => {
        if (updateData.certificates[index]) {
          updateData.certificates[index].photo = photo;
        }
      });
    }

    await caregiver.update(updateData);
    
    await caregiver.reload({
      include: [{
        model: User,
        as: 'user',
        attributes: ['id', 'firstName', 'lastName', 'email', 'phone', 'avatar']
      }]
    });

    logger.info(`更新护理员档案: ${req.user.email}`);

    res.status(200).json({
      status: 'success',
      message: '护理员档案更新成功',
      data: {
        caregiver
      }
    });
  } catch (error) {
    logger.error('更新护理员档案错误:', error);
    return next(new AppError('更新护理员档案失败', 500));
  }
};

// 获取所有护理员（管理员功能）
exports.getAllCaregivers = async (req, res, next) => {
  try {
    const where = {};
    
    // 状态过滤
    if (req.query.status) {
      where.status = req.query.status;
    }
    
    // 验证状态过滤
    if (req.query.verified !== undefined) {
      where.verified = req.query.verified === 'true';
    }
    
    const page = parseInt(req.query.page) || 1;
    const limit = parseInt(req.query.limit) || 10;
    const offset = (page - 1) * limit;
    
    const { count, rows: caregivers } = await Caregiver.findAndCountAll({
      where,
      include: [{
        model: User,
        as: 'user',
        attributes: ['id', 'firstName', 'lastName', 'email', 'phone', 'avatar']
      }],
      order: [['createdAt', 'DESC']],
      limit,
      offset
    });

    res.status(200).json({
      status: 'success',
      results: caregivers.length,
      total: count,
      page,
      totalPages: Math.ceil(count / limit),
      data: {
        caregivers
      }
    });
  } catch (error) {
    logger.error('获取护理员列表错误:', error);
    return next(new AppError('获取护理员列表失败', 500));
  }
};

// 获取单个护理员信息
exports.getCaregiver = async (req, res, next) => {
  try {
    const caregiver = await Caregiver.findByPk(req.params.id, {
      include: [{
        model: User,
        as: 'user',
        attributes: ['id', 'firstName', 'lastName', 'email', 'phone', 'avatar']
      }]
    });

    if (!caregiver) {
      return next(new AppError('护理员不存在', 404));
    }

    res.status(200).json({
      status: 'success',
      data: {
        caregiver
      }
    });
  } catch (error) {
    logger.error('获取护理员信息错误:', error);
    return next(new AppError('获取护理员信息失败', 500));
  }
};

// 搜索护理员
exports.searchCaregivers = catchAsync(async (req, res, next) => {
  const {
    location,
    radius = 10,
    skills,
    minRating = 0,
    maxPrice,
    availability,
    petTypes,
    emergencyService,
    overnightCare
  } = req.query;

  // 构建查询条件
  let query = {
    status: 'active',
    isVerified: true
  };

  // 地理位置搜索
  if (location) {
    const [lng, lat] = location.split(',').map(Number);
    if (lng && lat) {
      query['serviceArea.coordinates'] = {
        $near: {
          $geometry: {
            type: 'Point',
            coordinates: [lng, lat]
          },
          $maxDistance: radius * 1000 // 转换为米
        }
      };
    }
  }

  // 技能筛选
  if (skills) {
    const skillArray = skills.split(',');
    query.skills = { $in: skillArray };
  }

  // 评分筛选
  if (minRating > 0) {
    query['stats.averageRating'] = { $gte: minRating };
  }

  // 价格筛选
  if (maxPrice) {
    query['pricing.baseRate'] = { $lte: maxPrice };
  }

  // 紧急服务
  if (emergencyService === 'true') {
    query['availability.acceptsEmergency'] = true;
  }

  // 过夜护理
  if (overnightCare === 'true') {
    query['availability.acceptsOvernight'] = true;
  }

  // 宠物类型
  if (petTypes) {
    const petTypeArray = petTypes.split(',');
    query.skills = { $in: petTypeArray };
  }

  const features = new APIFeatures(Caregiver.find(query).populate('user', 'name avatar'), req.query)
    .sort('-stats.averageRating -stats.totalOrders')
    .limitFields()
    .paginate();

  const caregivers = await features.query;

  // 如果有可用性要求，进一步筛选
  let filteredCaregivers = caregivers;
  if (availability) {
    const availabilityDate = new Date(availability);
    filteredCaregivers = [];
    
    for (const caregiver of caregivers) {
      const isAvailable = await caregiver.checkAvailability(availabilityDate, availabilityDate);
      if (isAvailable) {
        filteredCaregivers.push(caregiver);
      }
    }
  }

  res.status(200).json({
    status: 'success',
    results: filteredCaregivers.length,
    data: {
      caregivers: filteredCaregivers
    }
  });
});

// 更新可用性
exports.updateAvailability = catchAsync(async (req, res, next) => {
  const caregiver = await Caregiver.findOne({ user: req.user.id });
  if (!caregiver) {
    return next(new AppError('护理员档案不存在', 404));
  }

  const { availability } = req.body;
  
  caregiver.availability = {
    ...caregiver.availability,
    ...availability
  };

  await caregiver.save();

  res.status(200).json({
    status: 'success',
    data: {
      availability: caregiver.availability
    }
  });
});

// 添加不可用日期
exports.addUnavailableDate = catchAsync(async (req, res, next) => {
  const caregiver = await Caregiver.findOne({ user: req.user.id });
  if (!caregiver) {
    return next(new AppError('护理员档案不存在', 404));
  }

  const { startDate, endDate, reason } = req.body;
  
  await caregiver.addUnavailableDate(new Date(startDate), new Date(endDate), reason);

  res.status(200).json({
    status: 'success',
    message: '不可用日期已添加'
  });
});

// 更新定价
exports.updatePricing = catchAsync(async (req, res, next) => {
  const caregiver = await Caregiver.findOne({ user: req.user.id });
  if (!caregiver) {
    return next(new AppError('护理员档案不存在', 404));
  }

  const { pricing } = req.body;
  
  caregiver.pricing = {
    ...caregiver.pricing,
    ...pricing
  };

  await caregiver.save();

  res.status(200).json({
    status: 'success',
    data: {
      pricing: caregiver.pricing
    }
  });
});

// 获取护理员统计信息
exports.getCaregiverStats = catchAsync(async (req, res, next) => {
  const stats = await Caregiver.aggregate([
    {
      $group: {
        _id: null,
        totalCaregivers: { $sum: 1 },
        activeCaregivers: {
          $sum: { $cond: [{ $eq: ['$status', 'active'] }, 1, 0] }
        },
        verifiedCaregivers: {
          $sum: { $cond: ['$isVerified', 1, 0] }
        },
        averageRating: { $avg: '$stats.averageRating' },
        totalOrders: { $sum: '$stats.totalOrders' },
        totalEarnings: { $sum: '$stats.totalEarnings' }
      }
    }
  ]);

  // 按技能分组统计
  const skillStats = await Caregiver.aggregate([
    { $unwind: '$skills' },
    {
      $group: {
        _id: '$skills',
        count: { $sum: 1 }
      }
    },
    { $sort: { count: -1 } }
  ]);

  // 按地区分组统计
  const locationStats = await Caregiver.aggregate([
    {
      $group: {
        _id: '$serviceArea.city',
        count: { $sum: 1 }
      }
    },
    { $sort: { count: -1 } },
    { $limit: 10 }
  ]);

  res.status(200).json({
    status: 'success',
    data: {
      overview: stats[0] || {},
      skillDistribution: skillStats,
      locationDistribution: locationStats
    }
  });
});

// 验证护理员（管理员功能）
exports.verifyCaregiver = catchAsync(async (req, res, next) => {
  const { verified, verificationNotes } = req.body;
  
  const caregiver = await Caregiver.findByIdAndUpdate(
    req.params.id,
    {
      isVerified: verified,
      'verification.status': verified ? 'verified' : 'rejected',
      'verification.verifiedAt': verified ? new Date() : undefined,
      'verification.verifiedBy': req.user.id,
      'verification.notes': verificationNotes
    },
    { new: true }
  ).populate('user', 'name email');

  if (!caregiver) {
    return next(new AppError('护理员不存在', 404));
  }

  res.status(200).json({
    status: 'success',
    data: {
      caregiver
    }
  });
});

// 激活/禁用护理员（管理员功能）
exports.toggleCaregiverStatus = catchAsync(async (req, res, next) => {
  const { status } = req.body;
  
  const caregiver = await Caregiver.findByIdAndUpdate(
    req.params.id,
    { status },
    { new: true }
  ).populate('user', 'name email');

  if (!caregiver) {
    return next(new AppError('护理员不存在', 404));
  }

  res.status(200).json({
    status: 'success',
    data: {
      caregiver
    }
  });
});

// 删除护理员档案
exports.deleteProfile = catchAsync(async (req, res, next) => {
  const caregiver = await Caregiver.findOne({ user: req.user.id });
  if (!caregiver) {
    return next(new AppError('护理员档案不存在', 404));
  }

  // 检查是否有进行中的订单
  const activeOrders = await Order.countDocuments({
    caregiver: caregiver._id,
    status: { $in: ['confirmed', 'in_progress'] }
  });

  if (activeOrders > 0) {
    return next(new AppError('您还有进行中的订单，无法删除档案', 400));
  }

  // 软删除
  caregiver.status = 'deleted';
  caregiver.deletedAt = new Date();
  await caregiver.save();

  // 更新用户角色
  await User.findByIdAndUpdate(req.user.id, { role: 'user' });

  res.status(204).json({
    status: 'success',
    data: null
  });
});

// 获取护理员收入统计
exports.getEarningsStats = catchAsync(async (req, res, next) => {
  const caregiver = await Caregiver.findOne({ user: req.user.id });
  if (!caregiver) {
    return next(new AppError('护理员档案不存在', 404));
  }

  const { period = 'month' } = req.query;
  let dateRange = {};
  
  const now = new Date();
  switch (period) {
    case 'week':
      dateRange = {
        $gte: new Date(now.getFullYear(), now.getMonth(), now.getDate() - 7)
      };
      break;
    case 'month':
      dateRange = {
        $gte: new Date(now.getFullYear(), now.getMonth(), 1)
      };
      break;
    case 'year':
      dateRange = {
        $gte: new Date(now.getFullYear(), 0, 1)
      };
      break;
  }

  const earnings = await Order.aggregate([
    {
      $match: {
        caregiver: caregiver._id,
        status: 'completed',
        createdAt: dateRange
      }
    },
    {
      $group: {
        _id: {
          year: { $year: '$createdAt' },
          month: { $month: '$createdAt' },
          day: { $dayOfMonth: '$createdAt' }
        },
        totalEarnings: { $sum: '$payment.amount' },
        orderCount: { $sum: 1 }
      }
    },
    { $sort: { '_id.year': 1, '_id.month': 1, '_id.day': 1 } }
  ]);

  res.status(200).json({
    status: 'success',
    data: {
      earnings,
      totalEarnings: caregiver.stats.totalEarnings,
      totalOrders: caregiver.stats.totalOrders
    }
  });
});